// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 生成二维码
    generateQRCode();
    
    // 表单提交处理
    handleFormSubmit();
    
    // 平滑滚动
    handleSmoothScroll();
    
    // 添加滚动动画
    handleScrollAnimation();
});

// 生成二维码
function generateQRCode() {
    const qrcodeContainer = document.getElementById('qrcode');
    if (qrcodeContainer) {
        // 使用当前页面URL生成二维码
        new QRCode(qrcodeContainer, {
            text: window.location.href,
            width: 128,
            height: 128,
            colorDark: '#2c3e50',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        });
    }
}

// 处理表单提交
function handleFormSubmit() {
    const form = document.getElementById('joinForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const formData = {
                name: document.getElementById('name').value,
                email: document.getElementById('email').value,
                phone: document.getElementById('phone').value,
                interest: document.getElementById('interest').value,
                message: document.getElementById('message').value
            };
            
            // 模拟发送邮件（实际项目中需要后端支持）
            simulateEmailSend(formData);
            
            // 显示成功消息
            showSuccessMessage();
            
            // 重置表单
            form.reset();
        });
    }
}

// 模拟发送邮件
function simulateEmailSend(data) {
    // 在实际项目中，这里应该调用后端API发送邮件
    console.log('准备发送邮件到社团邮箱:', data);
    
    // 模拟邮件内容
    const emailContent = `
        新的志愿者申请：
        
        姓名：${data.name}
        邮箱：${data.email}
        电话：${data.phone}
        感兴趣方向：${getInterestText(data.interest)}
        留言：${data.message}
        
        申请时间：${new Date().toLocaleString('zh-CN')}
    `;
    
    // 这里可以调用邮件API
    // 例如：fetch('/api/send-email', { method: 'POST', body: JSON.stringify({ content: emailContent }) })
}

// 获取兴趣方向的中文文本
function getInterestText(interest) {
    const interestMap = {
        'elderly': '关爱老人',
        'children': '儿童教育',
        'environment': '环境保护',
        'community': '社区服务',
        'other': '其他'
    };
    return interestMap[interest] || interest;
}

// 显示成功消息
function showSuccessMessage() {
    // 创建成功提示
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 100px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <strong><i class="fas fa-check-circle me-2"></i>申请成功！</strong>
        <p class="mb-0">我们会尽快与您联系，感谢您的关注！</p>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动关闭
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 3000);
}

// 处理平滑滚动
function handleSmoothScroll() {
    // 为导航链接添加平滑滚动
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            const targetSection = document.querySelector(targetId);
            
            if (targetSection) {
                const offsetTop = targetSection.offsetTop - 70; // 考虑固定导航栏高度
                window.scrollTo({
                    top: offsetTop,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 处理滚动动画
function handleScrollAnimation() {
    // 创建Intersection Observer
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in');
            }
        });
    }, observerOptions);
    
    // 观察所有需要动画的元素
    const animatedElements = document.querySelectorAll('.timeline-item, .benefit-item, .gallery-item');
    animatedElements.forEach(el => {
        observer.observe(el);
    });
}

// 图片点击放大功能
document.addEventListener('DOMContentLoaded', function() {
    const galleryItems = document.querySelectorAll('.gallery-item img');
    
    galleryItems.forEach(img => {
        img.addEventListener('click', function() {
            // 创建模态框
            const modal = document.createElement('div');
            modal.className = 'modal fade show';
            modal.style.display = 'block';
            modal.style.backgroundColor = 'rgba(0,0,0,0.9)';
            modal.innerHTML = `
                <div class="modal-dialog modal-xl modal-dialog-centered">
                    <div class="modal-content bg-transparent border-0">
                        <div class="modal-body text-center p-0">
                            <img src="${this.src}" class="img-fluid" style="max-height: 80vh;">
                            <button type="button" class="btn-close btn-close-white position-absolute" 
                                    style="top: 10px; right: 10px; z-index: 1;" 
                                    onclick="this.closest('.modal').remove()"></button>
                        </div>
                    </div>
                </div>
            `;
            
            // 点击背景关闭
            modal.addEventListener('click', function(e) {
                if (e.target === modal) {
                    modal.remove();
                }
            });
            
            document.body.appendChild(modal);
        });
    });
});

// 导航栏滚动效果
window.addEventListener('scroll', function() {
    const navbar = document.querySelector('.navbar');
    if (window.scrollY > 50) {
        navbar.classList.add('shadow');
    } else {
        navbar.classList.remove('shadow');
    }
});

// 响应式导航栏关闭
document.addEventListener('DOMContentLoaded', function() {
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    const navbarCollapse = document.querySelector('.navbar-collapse');
    
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (window.innerWidth < 992) {
                const bsCollapse = new bootstrap.Collapse(navbarCollapse, {
                    toggle: false
                });
                bsCollapse.hide();
            }
        });
    });
});
